<template>
  <el-dialog
    title="绑定权限"
    :visible.sync="isShow"
    width="50%"
    :before-close="handleClose"
  >
    <el-tree
      ref="rightsTree"
      :data="checkedKeys"
      show-checkbox
      node-key="id"
      :check-strictly="true"
      :default-checked-keys="defaultCheckedKeys"
      @check="handleCheckChange"
      :props="defaultProps"
      @check-change="checkChange"
    >
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button class="normal-btn" @click="handleClose">取 消</el-button>
      <el-button type="warning" @click="sureBtn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import serve from "@/api/jurisdiction";

export default {
  data() {
    return {
      checkedKeys: [],
      defaultCheckedKeys: [],
      queryParam: {
        name: "",
        comment: "",
        id: ""
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      updateData: []
    };
  },
  props: {
    isShow: {
      type: Boolean,
      default() {
        return false;
      }
    },
    id: {
      type: String,
      default() {
        return "";
      }
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        this.updateData = [];
        this.getPermissionList();
        this.jurisdictionHandle();
      }
    }
  },
  created() {},
  methods: {
    handleCheckChange(checkedNodes, checkedKeys) {
      this.updateData = checkedKeys.checkedKeys;
    },
    handleClose() {
      this.$emit("closeModel", false);
    },
    // 绑定权限方法
    async jurisdictionHandle() {
      //比对角色已选菜单
      let allList;
      await serve.permissionNavigationListServe().then(res => {
        if (res.code === 200) {
          allList = res.data.map(item => {
            return item.id;
          });
        }
      });
      serve.permissionNavigationListServe({ roleId: this.id }).then(res => {
        const newCheckedKeys = [];
        res.data.map(result => {
          if (allList.indexOf(result.id) !== -1) {
            newCheckedKeys.push(result.id);
          }
        });
        this.defaultCheckedKeys = newCheckedKeys;
        this.updateData = newCheckedKeys;
        this.$nextTick(() => {
          this.$refs.rightsTree.setCheckedKeys(this.defaultCheckedKeys);
        });
      });
    },
    // 全部权限
    getPermissionList() {
      serve.permissionNavigationListServe().then(res => {
        this.checkedKeys = JSON.parse(JSON.stringify(this.toTree(res.data)));
      });
    },
    toTree(data) {
      const result = [];
      if (!Array.isArray(data)) {
        return result;
      }
      data.forEach(item => {
        delete item.children;
      });
      const map = {};
      data.forEach(item => {
        map[item.id] = item;
      });
      data.forEach(item => {
        const parent = map[item.pid];
        if (parent) {
          item.label = item.menuName;
          (parent.children || (parent.children = [])).push(item);
        } else {
          item.label = item.menuName;
          result.push(item);
        }
      });
      return result;
    },
    checkChange(a, b) {
      //如果为取消
      if (b === false) {
        //如果当前节点有子集
        if (a.children) {
          //循环子集将他们的选中取消
          a.children.map(item => {
            this.$refs.rightsTree.setChecked(item.id, false);
          });
        }
      } else {
        //否则(为选中状态)
        //判断父节点id是否为空
        if (a.pid !== 0) {
          //如果不为空则将其选中
          this.$refs.rightsTree.setChecked(a.pid, true);
        }
      }
      this.tableData = this.$refs.rightsTree.getCheckedNodes();
    },
    sureBtn() {
      //返回选中子节点的key
      let child = this.$refs.rightsTree.getCheckedKeys();
      //返回选中子节点的父节点的key
      let parent = this.$refs.rightsTree.getHalfCheckedKeys();
      let checkNode = child.concat(parent);
      console.log(checkNode.join(","));
      serve
        .addDutyNavBindingServe({
          grantMenuIdList: checkNode.length === 0 ? "" : checkNode.join(","),
          id: this.id
        })
        .then(res => {
          if (res.code === 200) {
            this.$emit("closeModel", false);
            this.$notify.success("权限绑定成功", 2);
          } else {
            this.$notify.error(res.msg, 2);
          }
        });
    }
  }
};
</script>

<style scoped></style>
